<template>
  <div id="search-box-first" transition="fadeInLeft">
    <div v-show="!isShow">
      <loading :show="true"></loading>
    </div>

    <div id="soso" ref="soso" class="uou" :class="[{ mout: amout }, this.fun.getPhoneEnv() == 3 ? 'pcStyle' : '']">
      <div class="search">
        <div class="back" @click="goback"><i class="fa fa-angle-left"></i></div>
        <div class="search-box">
          <form @submit.prevent action="#" id="search-form">
            <input type="search" ref="search_input" placeholder="请输入内容" @keypress="enterSearch" v-model="inputs" @focus="hidebox" @blur="searchBlur" />
          </form>
          <i ref="search_icon" class="iconfont icon-sousuo1" style="color: #ccc;" @click="search"></i>
        </div>
        <div style="position: absolute; right: 1rem;">
          <i class="fa fa-th-large" v-show="view" @click="$store.commit('views')"></i>
          <i class="fa fa-th-list" v-show="!view" @click="$store.commit('views')"></i>
        </div>
      </div>

      <!-- 搜索历史 -->
      <div>
        <!-- 动态获取到soso的高度，需要 元素显示隐藏，页面重绘 -->
        <div v-show="pageReload"></div>
        <transition name="fateOut" v-on:enter="fateOutEnter" v-on:after-leave="fateOutLeave">
          <sarchHistory v-show="showHistory" :storageName="storageName" ref="searchHistory" @clickTag="serachTag" @popTag="getSosoHeight"></sarchHistory>
        </transition>
      </div>
      <c-sort :show="true" :pluginShow="pluginShow" :typeName="this.$route.name"  @sortIn="sortOut" @showscreen="showbox" text="搜索结果"></c-sort>
    </div>
    <div :style="{ height: sosoH + 'px', display: block }"></div>
    <van-pull-refresh v-model="isLoading" @refresh="loadTop" success-text="刷新成功">
      <yz-blank v-show="isShow" :datas="goods" text="没找到相关产品，换个词搜搜吧"></yz-blank>
      <d-list @load="getMoreData" :finished="!isLoadMore" :loading="loading" :showStatusText="false">
        <c-goodsList :goods="goods" :goods_template="goods_template" :goods_style_set='goods_style_set' text="搜索结果" class="osll" :loading="!isLoadMore" :orderField="order_field"></c-goodsList>
      </d-list>
    </van-pull-refresh>

    <U_backup :btnFlag="btnFlag" :id="1" :datas="btnData"></U_backup>

    <goodScreen v-model="show" @clone="cloneGoodScreen" :showCategory="istypeclass" ref="goodScreen">
      <!-- 筛选弹窗 -->
    </goodScreen>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import cGoodsList from "components/goodsList";
import cSort from "components/sort";
import U_backup from "components/new_diy/backup";
import sarchHistory from "components/searchHistory";
import DList from "@/components/dlist";
import loading from "components/loading";
import yzBlank from "components/ui_components/yz_blank";
import goodScreen from "components/ui_components/yz_goodScreen";
// import { scrollMixin } from '../utils/mixin';

export default {
  // mixins: [scrollMixin], //加载更多
  data() {
    return {
      show: false,
      istypeclass: false, //是否点击分类进来的
      isShow: true,
      pluginType:'', //插件类型
      title: "搜索",
      inputs: "",
      amout: false,
      order_by: "",
      order_field: "",

      typestring: "", //搜索分类id
      namestring: "",
      namekey: null,
      classificationshow: false,

      btnFlag: false, //显示回到顶部
      btnData: {
        button_size: 40,
        over_top: 500,
        position_location: "right",
        icon_url: ""
      },

      loading: false,
      goods: [],
      page: 1, //分页数，当前页数
      isLoadMore: true, //判断是否要加载更多的标志
      total_page: 0, //总页数

      goods_template: "",
      goods_style_set: {},
      // 下拉刷新
      isLoading: false,
      sosoH: 84, // 头部栏的高度
      pageReload: false, // 通过if刷新页面
      storageName: "searchHistory", // storage的key
      showHistory: false, // 显示历史搜索记录
      deliverId: 0, //自提点id

      searchScreen: {},
    };
  },
  computed: {
    ...mapState(["view"]),
    zoneId() {
      if (this.$store.state.zoneId == "") {
        this.$store.commit("setZoneId", window.localStorage.getItem("zoneId"));
      }
      return this.$store.state.zoneId;
    },
    pluginShow() {
      if(this.pluginType === 'collection-center') {
        return false;
      } else {
        return true;
      }
    }
  },
  mounted() {
    window.searchScrollTop = 0;
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === "goods" || from.name === "grab_group" || from.name === "newRetailSalesGood") {
      if (toGoodListIOS) {
        toGoodListIOS({ body: "toGoodListIOS" });
      }
    }
    next();
  },
  beforeRouteLeave(to, from, next) {
    window.searchScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    next();
  },
  methods: {
    cloneGoodScreen(e){
      console.log(e)
      this.searchScreen = e;
      this.gotoSearch();
    },
    ...mapMutations(["views"]),
    lastScrollHeight() {
      if (window.location.href.indexOf("#/search?") > -1) {
        setTimeout(() => {
          window.scrollTo(0, window.searchScrollTop);
        }, 200);
      }
    },

    // 动态获取头部栏的高度
    getSosoHeight() {
      this.pageReload = !this.pageReload;
      this.$nextTick(() => {
        this.sosoH = this.$refs.soso.offsetHeight;
      });
    },
    //通用功能
    showbox() {
      this.show = !this.show;
    },
    fateOutEnter() {
      this.getSosoHeight();
    },
    fateOutLeave() {
      this.getSosoHeight();
    },
    hidebox() {
      this.show = false;
      this.searchHistoryList = window.localStorage.getItem(this.storageName) ? JSON.parse(window.localStorage.getItem(this.storageName)) : [];
      if (this.searchHistoryList.length > 0) {
        this.showHistory = true;
      }
      // this.getSosoHeight();
    },
    searchBlur() {
      this.showHistory = false;
      // this.getSosoHeight();
    },
    enterSearch(event) {
      if (event.keyCode === 13) {
        //如果按的是enter键
        event.preventDefault();
        this.search();
      }
    },

    sortOut(e) {
      this.hidebox();
      if (this.goods.length == 0) {
        return;
      }
      this.order_field = e.order_field;
      this.order_by = e.order_by;
      this.gotoSearch();
    },
    search() {
      //搜索页聚焦状态下搜索关键词获取不到
      if (this.$refs.search_input) {
        this.$refs.search_input.blur();
      }
      // 添加搜索记录
      if (this.$refs.searchHistory) {
        this.$refs.searchHistory.appendKeywords(this.inputs);
        this.getSosoHeight();
      }
      this.$nextTick(() => {
        this.gotoSearch();
      });
    },

    // 点击tag搜索
    serachTag(data) {
      this.inputs = data;
      this.search();
    },
    goback() {
      if(this.inputs) {
        this.inputs = '';
        // this.search();
      }
      this.$refs.goodScreen.resetnames();
      this.searchScreen = {};
      this.$router.go(-1);
    },
    slider() {
      window.onscroll = () => {
        let top = document.documentElement.scrollTop || document.body.scrollTop;

        if (top > 80 && !this.showHistory) {
          this.$refs.search_input.blur();
        }
        if (top >= 80) {
          this.amout = true;
          this.btnFlag = true;
        } else {
          this.amout = false;
          this.btnFlag = false;
        }
      };
    },
    loadTop() {
      this.gotoSearch();
    },
    gotoSearch() {
      this.isShow = false;
      this.page = 1;
      this.goods = [];
      this.loading = true;
      let price;
      if(this.searchScreen.top || this.searchScreen.mini){
        if(!this.searchScreen.mini){
          price = this.searchScreen.top
        }else{
          price = `${ this.searchScreen.mini }${ this.searchScreen.top ?','+this.searchScreen.top:this.searchScreen.top?this.searchScreen.top:'' }`
        }
      }
      let json = {
        "search[keyword]": this.inputs,
        page: this.page,
        order_field: this.order_field,
        order_by: this.order_by,
        "search[couponid]": this.$route.params.coupon || '',
        "search[as_id]": this.zoneId || '',
        "search[brand_id]": this.searchScreen.brandId||'',
        "search[product_attr]": this.searchScreen.attrstr||'',
        "search[filtering]": this.searchScreen.filterId||'',
        "search[category]": this.searchScreen.typestring||'',
        "search[price_range]":price || ""
      };
      if(this.$route.params.new_coupon_id){
        json["search[new_coupon_id]"] = this.$route.params.new_coupon_id;
      }
      if (this.$route.query.plugin_id == 1) {
        // 筛选平台商品
        json["search[plugin_id]"] = 0;
      }
      let _url = "";
      if (!this.fun.isTextEmpty(this.$route.query.fromPage) && this.$route.query.fromPage == 1) {
        _url = "plugin.pending-order.frontend.wholesale-area.goods-list";
      } else if (this.$route.name == "selfPickSearch") {
        _url = "plugin.supplier.frontend.category.search-goods";
      } else if (this.$route.query.CommodityRights == "CommodityRights") {
        _url = "plugin.love-speed-pool.frontend.goods.getList";
      }else if(this.$route.query.plugin_type && this.$route.query.plugin_type == 'vending_machine') {
        _url = "plugin.automat.frontend.goods.searchGoods";
        json['automat_machine_id'] = this.$route.query.machineId;
        json["search[automat_machine_id]"]=this.$route.query.machineId;
      } else if( this.$route.name == 'coffee_machine_search'){
        _url = "plugin.coffee-machine.frontend.goods.searchGoods";
        json["search[coffee_machine_id]"]=this.$route.params.machine_id;
      }else if(this.$route.query.plugin_type && this.$route.query.plugin_type == 'collection-center'){ //数字藏品
        _url = "plugin.collection-center.frontend.controllers.goods.goods.index";
      } else if (this.$route.name == 'distributionCouponSearch') {
          // 配销券搜索页
        _url = "plugin.distribution-coupon.api.goods.search-goods"
      } else if (this.$route.name == 'system_integration_search') {
        _url = "plugin.body-health-check.api.goods.search-goods"
      } else {
        _url = "goods.goods.search-goods";
        if(this.$route.query.plugin_type && this.$route.query.plugin_type == 'map-marker'){ //地图标注
          json.plugin_id = '189'
        }
      }
      if(this.$route.name == 'distributionCouponSearch'){
        json.coupon_id = this.$route.params.coupon_id
      }
      if (this.$route.name == 'LeaseSearch'){
        // 租赁中台商品
        _url = "plugin.yz-supply-lease.api.goods.goods-list";
        let yzSupplyArea = JSON.parse(window.localStorage.getItem('yzSupplyArea'));
        json = {};
        json = {
          page: this.page,
          "search[keyword]": this.inputs,
          "search[brand_id]": this.searchScreen.brandId||'',
          "search[supplier_id]": this.searchScreen.supplier_id||'',
          "search[cate]": this.searchScreen.typestring||'',
          "search[region]": this.$route.query.region_id ? this.$route.query.region_id : (yzSupplyArea && yzSupplyArea.region_id ? yzSupplyArea.region_id : ''),
          "sort[type]": this.order_field,
          "sort[direction]": this.order_by,
        }
      }
      $http.get(_url, json, "...").then(res => {
        this.isShow = true;
        this.isLoading = false;
        if (res.result == 1) {
          let data = res.data;
          window.scrollTo(0, 0);
          this.isLoadMore = true;
          this.loading = false;
          this.total_page = res.data.last_page || 0;
          this.goods_template = res.data.goods_template;
          this.goods_style_set = res.data.goods_style_set||{};
          this.goods = res.data.data;
          if(this.pluginType == 'collection-center') {
            this.goods = data.goods_list.data;
            this.total_page = data.goods_list.last_page || 0;
          }
          // 搜索结果为空
          if (this.total_page <= 1) {
            this.isLoadMore = false;
          }
          // 设置分享信息
          this.shareConfigs({
            inputs: this.inputs
            // order_field: this.order_field,
            // order_by: this.order_by,
            // zoneId: this.zoneId,
            // brandId: this.brandId,
            // attrstr: this.attrstr.toString(),
            // filterId: this.filterId.toString(),
            // typestring: this.typestring
          });
        } else {
          this.goods = [];
          this.isLoadMore = false;
          this.isShow = true;
        }
      });
    },
    getMoreData() {
      if (this.loading === true || this.isLoadMore === false) {
        return;
      }

      console.log("加载更多启动");
      this.loading = true; // 防止多次请求分页数据
      if (this.page >= this.total_page) {
        this.isLoadMore = false;
        console.log("没了");
      } else {
        this.page += 1;
        let price;
        if(this.searchScreen.top || this.searchScreen.mini){
          if(!this.searchScreen.mini){
            price = this.searchScreen.top
          }else{
            price = `${ this.searchScreen.mini }${ this.searchScreen.top ?','+this.searchScreen.top:this.searchScreen.top?this.searchScreen.top:'' }`
          }
        }
        let json = {
          "search[keyword]": this.inputs,
          page: this.page,
          order_field: this.order_field,
          order_by: this.order_by,
          "search[couponid]": this.$route.params.coupon,
          "search[as_id]": this.zoneId,
          "search[brand_id]": this.searchScreen.brandId||'',
          "search[product_attr]": this.searchScreen.attrstr||'',
          "search[filtering]": this.searchScreen.filterId||'',
          "search[category]": this.searchScreen.typestring||'',
          "search[price_range]":price || ""
        };
        if (this.$route.query.plugin_id == 1) {
          // 筛选平台商品
          json["search[plugin_id]"] = 0;
        }
        let _url = "";
        if (!this.fun.isTextEmpty(this.$route.query.fromPage) && this.$route.query.fromPage == 1) {
          _url = "plugin.pending-order.frontend.wholesale-area.goods-list";
        } else if (this.$route.name == "selfPickSearch") {
          _url = "plugin.supplier.frontend.category.search-goods";
        } else if (this.$route.query.CommodityRights == "CommodityRights") {
          _url = "plugin.love-speed-pool.frontend.goods.getList";
        } else if (this.$route.query.plugin_type && this.$route.query.plugin_type == 'vending_machine')  {
          //售货机
          _url = "plugin.automat.frontend.goods.searchGoods";
          json['automat_machine_id'] = this.$route.query.machineId;
          json["search[automat_machine_id]"]=this.$route.query.machineId;
        } else if( this.$route.name == 'coffee_machine_search'){
          _url = "plugin.coffee-machine.frontend.goods.searchGoods";
          json["search[coffee_machine_id]"]=this.$route.params.machine_id;
        } else if (this.$route.name == 'distributionCouponSearch') {
          // 配销券搜索页
          _url = "plugin.distribution-coupon.api.goods.search-goods"
        }  else {
          _url = "goods.goods.search-goods";
        }
        if(this.$route.name == 'distributionCouponSearch'){
          json.coupon_id = this.$route.params.coupon_id
        }
        if (this.$route.name == 'LeaseSearch'){
          // 租赁中台商品
          _url = "plugin.yz-supply-lease.api.goods.goods-list";
          json = {};
          json = {
            page: this.page,
            "search[keyword]": this.inputs,
            "search[brand_id]": this.searchScreen.brandId||'',
            "search[supplier_id]": this.searchScreen.supplier_id||'',
            "search[cate]": this.searchScreen.typestring||'',
            "search[region]": this.$route.query.region_id||'',
            "sort[type]": this.order_field,
            "sort[direction]": this.order_by,
          }
        }
        $http
          .get(_url, json, "...")
          .then(res => {
            this.isLoadMore = true;
            this.loading = false;
            if (res.result == 1) {
              let nextPageData = res.data.data;
              this.goods = this.goods.concat(nextPageData); //进行数组拼接
            } else {
              this.page = this.page - 1;
              this.isLoadMore = false;
            }
          })
          .catch(error => {
            console.log(error);
          });
      }
    },
    initData() {
      this.pluginType = this.$route.query.plugin_type;
    },
    shareConfigs(_data) {
      let mid = this.fun.getKeyByMid();
      let _url = this.fun.getSiteRoot() + "/addons/yun_shop/?menu#/search?i=" + this.fun.getKeyByI() + "&mid=" + mid;
      Object.keys(_data).forEach(key => {
        if (_data[key]) {
          _url = `${_url}&${key}=${_data[key]}`;
        }
      });
      this.fun.wxShare(
        "",
        {},
        {
          link: _url
        },
        data => {}
      );
    },
    getShareConfig() {
      let _arr = this.$route.query;
      let getKeys = ["inputs", "order_field", "order_by", "zoneId"];
      let searchScreenKey = ["brandId", "attrstr", "filterId", "typestring"];
      Object.keys(_arr).forEach(key => {
        if (getKeys.indexOf(key) > -1) {
          this[key] = _arr[key];
        }
        if (searchScreenKey.indexOf(key) > -1) {
          this.searchScreen[key] = _arr[key];
        }
      });
    },
    async getNowPackageDeliver() {
      //确定关联自提点
      let deliverIDStorage = sessionStorage.getItem("deliverId") || null; //获取当前会话是否存储了自提点id
      let _href = window.location.href; //当前链接
      let lat, lng;
      if (deliverIDStorage) {
        //sessionStorage 有值，说明某个页面之前有请求记录过，可直接请求分类
        if (deliverIDStorage != this.deliverId) {
          this.deliverId = deliverIDStorage;
          this.search();
        }
        return;
      } else if (_href.indexOf("deliverId") > -1) {
        let _dID = this.fun.getKey("deliverId"); //获取链接上的参数，自提点id
        this.deliverId = _dID;
      } else {
        await this.fun
          .getLocation("正在定位中，请稍等")
          .then(res => {
            lat = res.point.lat;
            lng = res.point.lng;
          })
          .catch(err => {
            console.log("定位error：：", err);
          });
      }
      let _json = {};
      if (lat) {
        _json = {
          lng: lng || "",
          lat: lat || ""
        };
      }
      if (this.deliverId) {
        _json.deliver_id = this.deliverId;
      }

      $http.get("plugin.package-deliver.frontend.decorate-deliver.getNowPackageDeliver", _json, ".").then(
        response => {
          if (response.result === 1) {
            this.search();
            this.deliverId = response.data.id;
            window.sessionStorage.setItem("deliverId", response.data.id); //储存到sessionStorage
            this.fun.wxShare();
          } else {
            this.$toast(response.msg);
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
  },
  created() {
    // this.search();
    if (this.$route.params.fromHome !== 1) {
      this.goods = [];
      this.inputs = "";
      if (this.$route.name == "selfPickSearch") {
        this.getNowPackageDeliver(); //可优化成promis，流程
      } else {
        this.search();
      }
    }
    console.log(this.$route.name);
    // if (this.$route.params.coupon || this.$route.params.kyes) {
    //   console.log("created-----------------------");
    //   this.search(n);
    // }
  },
  activated() {
    if(this.$route.name == 'LeaseSearch'){

    }
    this.getShareConfig();
    if ((this.$route.params.id != "" && !isNaN(this.$route.params.id)) || this.$route.query.cate_id) {
      this.searchScreen.typestring = this.$route.params.id || this.$route.query.cate_id;
      this.istypeclass = true;
      this.fun.setWXTitle("分类列表");
    }
    this.amout = false;
    this.show = false;
    this.slider();
    this.$nextTick(() => {
      this.sosoH = this.$refs.soso.offsetHeight;
    });
    if (this.$route.params.coupon || this.$route.params.kyes) {
      console.log("activated-----------------------");
      this.search();
    } else if(this.$route.params.new_coupon_id){
      this.search();
    } else if (this.$route.params.fromHome === 1) {
      this.inputs = "";
      if (this.$route.name == "selfPickSearch") {
        this.getNowPackageDeliver(); //可优化成promis，流程
      } else {
        this.search();
      }
    } else {
      this.lastScrollHeight();
      // let json = JSON.parse(window.localStorage.getItem('searchBrandJSON'));
      // let key = window.localStorage.getItem('searchBrandKey');
      // this.searchAgain(json);
      // this.inputs = key;
      // 不是从上一级点进的不清空
    }
    this.initData();

  },
  components: {
    cGoodsList,
    cSort,
    U_backup,
    sarchHistory,
    DList,
    loading,
    yzBlank,
    goodScreen
  }
};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
#search-box-first {
  width: 100%;

  .fade1-enter-active {
    transition: 0.3s;
  }

  .fade1-enter,
  .fade1-leave-to {
    opacity: 0;
    transform: translateX(100%);
  }

  .fade-enter-active,
  .fade-leave-active {
    transition: all 0.3s;
  }

  .fade-enter,
  .fade-leave-to {
    transform: translateX(100%);
  }

  .osll {
    min-height: 100vh;
    overflow: scroll;
  }

  .uou {
    position: fixed;
    z-index: 99;
    top: 0;
    transition: 0.2s;
    -webkit-transition: 0.2s;
  }

  .mout {
    top: -2.25rem;
  }
}

#search-box-first {
  .osll {
    min-height: 100vh;
    overflow: scroll;
  }

  .uou {
    width: 100%;
    position: fixed;
    z-index: 99;
    top: 0;
    transition: 0.2s;
    -webkit-transition: 0.2s;
    background: #fff;
  }

  .pcStyle {
    width: 375px;
  }

  #sort {
    /* line-height: 2.5rem; */
    font-size: 14px;
  }

  .mout {
    top: -2.25rem;
  }
}

.search {
  height: 2.875rem;
  line-height: 2.875rem;
  position: relative;
  display: flex;
  overflow: hidden;
  background: #fff;
  // border-bottom: 0.0625rem solid #f5f5f5;
  .back {
    width: 2.8125rem;

    i {
      line-height: 2.875rem;
      font-size: 1.5rem;
    }
  }

  .search-box {
    position: relative;
    display: flex;
    justify-content: space-between;
    width: 75%;
    margin-top: 0.5rem;
    padding: 0 0.625rem;
    background-color: #f2f2f2;
    height: 1.75rem;
    line-height: 1.75rem;
    border-radius: 0.875rem;

    #search-form {
      flex: 1;
      margin-right: 0.5rem;
    }

    input {
      width: 100%;
      line-height: 1.75rem;
      border: none;
      color: #333;
    }

    i {
      flex: 0 0 1.5rem;
    }
  }
}

.search::after {
  height: 1px;
  position: absolute;
  z-index: 0;
  bottom: 0;
  left: 0;
  content: "";
  width: 100%;
  background-image: linear-gradient(0deg, #f5f5f5 50%, transparent 0);
}

.fateOut-enter,
.fateOut-leave-to {
  opacity: 0;
  // transform: scaleY(0);
}

.fateOut-enter-to,
.fateOut-leave {
  opacity: 1;
  // transform: scaleY(1);
}

.fateOut-enter-active,
.fateOut-leave-active {
  transition: all 0.2s;
  transform-origin: top;
}
</style>
